<?

class sphinx
{
	protected static function get_index_data( $data, $keys )
	{
		$index_data['id'] = $data['sid'];

		foreach ( $keys as $alias => $key )
			$index_data[is_numeric($alias) ? $key : $alias] = is_array($data[$key]) ? implode(' ', $data[$key]) : (string)$data[$key];

		return $index_data;
	}

	public static function rt_add( $data, $keys, $index )
	{
		if ( $values = self::get_index_data($data, $keys) )
		{
			db_mysql::set_connection('sphinx');

			try
			{
				db_mysql::insert($values, $index);
			} catch( Exception $e ) {};
			db_mysql::set_connection();
		}
	}
	
	public static function rt_update( $sid, $data, $keys, $index )
	{
		if ( !$data['id'] = $sid ) return;

		if ( $values = self::get_index_data($data, $keys) )
		{
			db_mysql::set_connection('sphinx');
			try
			{
				db_mysql::insert($values, $index, true);
			} catch( Exception $e ) {};
			db_mysql::set_connection();
		}
	}

	public static function rt_delete( $sid, $index )
	{
		$sid = is_array($sid) ? $sid['sid'] : $sid;

		db_mysql::set_connection('sphinx');
		try
		{
			db_mysql::query('DELETE FROM ' . $index . ' WHERE id = ' . $sid);
		} catch( Exception $e ) {};
		db_mysql::set_connection();
	}

	public static function needs_reindex( $data, $index_columns )
	{
		foreach ( $data as $k => $v ) if ( in_array($k, $index_columns) )
			return true;

		return false;
	}

	public static function generate_id()
	{
		if ( config::all()->sphinx['id_generator'] == 'redis' )
		{
			return db_redis::inc('sphinx-auto-id');
		}
		else
		{
			str_replace('.', '', microtime(true)) . mt_rand(1000, 9999) . mt_rand(10, 99);
		}
	}

	/**
	 *
	 * @return SphinxClient
	 */
	public static function api_client()
	{
		$config = config::get('sphinx');
		$cl = new SphinxClient();
		
		$cl->SetServer ( $config['host'], $config['search_port'] );
		$cl->SetConnectTimeout ( 1 );
		$cl->SetArrayResult ( true );

		$cl->SetMatchMode ( SPH_MATCH_ALL );

		return $cl;
	}

	public static function search( $query, $index, $limit = 25, $offset = 0, $filters = array(), $sort = array() )
	{
		$cl = self::api_client();
		$cl->SetLimits ( $offset, $limit, ( $limit>1000 ) ? $limit : 1000 );

		if ( $filters ) foreach ( $filters as $filter => $value ) $cl->SetFilter($filter, is_array($value) ? $value : array($value) );
		if ( $sort ) $cl->SetSortMode(constant($sort[0]), $sort[1]);

		return $cl->Query ( $query, $index );
	}
}